package com.dly.blog.utile;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/17 15:52
 */
@Slf4j
public final class JsonUtils {

    /**
     * json -> object
     * @param jsonData
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T readFromJsonString(String jsonData, Class<T> clazz) {
        ObjectMapper om = new ObjectMapper();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        T result = null;
        try {
            result = om.readValue(jsonData, clazz);
        } catch (Exception e) {
            log.error("转化数据{}为{}失败", jsonData, clazz.getSimpleName(), e);
        }
        return result;
    }

    /**
     * json -> object
     * @param jsonData
     * @return
     * @param <T>
     */
    public static <T> T readFromJsonString(String jsonData, TypeReference<T> valueTypeRef) {
        ObjectMapper om = new ObjectMapper();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        T result = null;
        try {
            result = om.readValue(jsonData, valueTypeRef);
        } catch (Exception e) {
            log.error("转化数据{}失败", jsonData, e);
        }
        return result;
    }


    /**
     * object -> json
     * @param object
     * @return
     */
    public static String writeToJson(Object object) {
        if (Objects.isNull(object)) {
            return null;
        }
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String result = null;
        try {
            result = om.writeValueAsString(object);
        } catch (Exception e) {
            log.error("创建json数据错误：" + e + object);
        }
        return result;
    }


    private JsonUtils(){}

    public static JsonUtils getInstance() {
        return JsonUtils.JsonUtilsHolder.INSTANCE;
    }

    private static class JsonUtilsHolder {
        public static final JsonUtils INSTANCE = new JsonUtils();
    }
}
